package com.kykj.kykjyzw.config;

import com.kykj.kykjyzw.service.impl.RouteServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component//注入Spring
public class WebXIntercep  implements HandlerInterceptor {
    @Resource
    RouteServiceImpl routeService;
    //访问controller方法之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", request.getMethod());
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
        response.setHeader("Access-Control-Allow-Headers", request.getHeader("Access-Control-Request-Headers"));
        System.out.println("拦截器preHandle");
        String uname=request.getHeader("uname");
        ServletOutputStream outputStream = response.getOutputStream();//输出对象
        //如果用户名是zhangsan,有访问/v2/user 下所有的接口的权限
        if (routeService.isRoute(uname,request.getRequestURI())){ //符合权限
            return true;//允许通过拦截器
        }else {
                outputStream.write("{\"code\":-9999,\"msg\":\"权限不足\"}".getBytes());
            System.out.println(uname);
            System.out.println(routeService.isRoute(uname,request.getRequestURI()));
                return false;//不允许通过拦截器

        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception{
        System.out.println("拦截器postHandle");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在请求处理完成后记录结束时间，并计算处理时间
        System.out.println("拦截器afterCompletion");
    }
}
